/**
 * Created by Tuffy on 2016/11/30.
 */
'use strict';

var request = require('request');
var baseConfig = require('../resource/base-config');
module.exports = distributionService;

// 声明分发对象
function distributionService() {}

// get请求
distributionService.get = function (req, res, callback) {
            var url = req.query.url;
            var splitUrl = url.split('?');
            var query = '?';
            if (splitUrl.length > 1) {
                query += splitUrl[1];
            }
            get(splitUrl[0], query, req, callback);
};

// post 请求
distributionService.post = function (req, res, callback) {
            post(req.query.url, req, callback);
};

distributionService.index = function(req, res, callback) {
    post('/index', req, callback);
};

/**
 * get request
 * @param queryString
 * @param req
 * @param callback
 */
function get(url, queryString, req, callback) {
    var host = req.query.host;
    request.get({
        qs: parseUrlParams(queryString),
        json: true,
        url: baseConfig[host] + url
    }, function(err, res, body) {
        if (!err && res.statusCode === 200) {
            if (callback) {
                callback(body);
            }
        } else {
            callback({success: false, message: '请求异常'});

        }
    });

    // 解析url
    function parseUrlParams(url) {
        url = url.replace(/\?/gi, '');
        var urlArray = url.split('&');
        var params = {};
        for (var i = 0;i < urlArray.length; i++) {
            var item = urlArray[i];
            var itemArray = item.split('=');
            params[itemArray[0]] = itemArray[1];
        }
        return params;
    }
}

/**
 * post request
 * @param url
 * @param req
 * @param callback
 */
function post(url, req, callback) {
    var host = req.query.host;
    request.post({
        json: true,
        url: (baseConfig[host]) + url,
        form: req.body
    }, function(err, res, body) {
        if (!err && res.statusCode === 200) {
            var result = body;
            callback(result);
        } else {
            callback({success: false, message: '请求异常'});
        }
    });
}